<!-- <template>
    <div id="float-ball" @click='handleClick'>下载</div>
</template>

<script setup lang="ts">
import { ref } from 'vue';

import { GM_xmlhttpRequest } from '$';
// import { XLSX } from '$';
// import { monkeyWindow } from '$';
const XLSX = window.XLSX;
interface DatabaseConfig {
    appName: string;
    domain: string;
}

interface Database {
    [key: string]: DatabaseConfig;

}
const database = ref < new Map<string, DatabaseConfig>([[
    // 'bd_api': {
    //     appName: 'mysqldb037_bd_api',
    //     domain: 'my23227sa.mysql.jd.local'
    // },
    // bd_use: {
    //     'appName': 'mysqldb004_bd_use',
    //     'domain': 'my22679sa.mysql.jddb.com'
    // },
    // kong_ming: {
    //     'appName': 'mysqldb004_kong_ming',
    //     'domain': 'my22683sa.mysql.jddb.com'
    // },
    // 'bd_relation': {
    //     'appName': 'mysqldb084_bd_relation',
    //     'domain': 'my23145sa.mysql.jd.local'
    // },
    // 'performance_api': {
    //     'appName': 'mysqldb004_performance_api',
    //     'domain': 'my22672sa.mysql.jddb.com'
    // },
    // 'bd_data_api': {
    //     'appName': 'dada_db_bd_data_api',
    //     'domain': 'my23904sa.mysql.jd.local'
    // },
    // 'auth_center_new': {
    //     'appName': 'dada_db_auth_center_new',
    //     'domain': 'my23596sa.mysql.jd.local'
    // },
    'compass', {
        appName: "dada_db_compass",
        domain: "my23903sa.mysql.jd.local"
    }
]])
async function handleClick() {
    const active_database = document.querySelector('.dbsv5-tabs-tab.dbsv5-tabs-tab-with-remove.dbsv5-tabs-tab-active') as HTMLInputElement
    if (!active_database) {
        return
    }
    // 获取域名
    const domainName = active_database.querySelector('.dbsv5-tabs-tab-btn').textContent
    if (!domainName) {
        return
    }
    const databaseName = domainName.split('@')[0]
    const sql = await navigator.clipboard.readText()

    if (!sql.includes('select') && !sql.includes('SELECT')) {
        alert('不包含查询语句')
        return
    }
    const dataList: any[] = []
    const countQuery = fetchData({
        "appName": database.value.get(databaseName).appName,
        "dbName": databaseName,
        "domain": database.value[databaseName]['domain'],
        "sql": sql.replace(/select\s+.*?\s+from/i, 'SELECT COUNT(1) FROM').replace(/SELECT\s+.*?\s+FROM/i, 'SELECT COUNT(1) FROM'),
        "isDesensitization": 0
    })
    countQuery.then(res => {
        const count = res[0]['COUNT(1)']
        const num = count % 100 > 0 ? parseInt(count / 100) + 1 : parseInt(count / 100)
        console.log(num)
        for (let i = 0; i < num; i++) {
            const cur = sql.replace('\n', '').replace(';', '') + ` limit ${i * 100},100`
            console.log(database.value.bd_api)
            const request = {
                "appName": database.value[databaseName]['appName'],
                "dbName": databaseName,
                "domain": database.value[databaseName]['domain'],
                "sql": cur,
                "isDesensitization": 1
            }
            dataList.push(request)
        }
        fetchSequentialData(dataList).then(res => {
            const list = res.flat()
            console.log(list)
            const wb = XLSX.utils.book_new();
            const ws = XLSX.utils.json_to_sheet(list);
            XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
            XLSX.writeFile(wb, Date.now() + "-data.xlsx");
        })
    })


}

async function fetchSequentialData(dataList: any[]) {
    console.log(dataList)
    const results = [];
    for (const data of dataList) {
        try {
            const response = await fetchData(data);
            results.push(response);
            await sleep(1000)
        } catch (error) {
            console.error('请求出错:', error);
            results.push(null);
        }
    }
    return results;
}

function fetchData(data: any) {
    console.log(data)
    return new Promise((resolve, reject) => {
        GM_xmlhttpRequest({
            method: 'POST',
            url: 'https://dbsv5api.jd.com/dbquery/queryData?_t=' + Date.now(),
            data: JSON.stringify(data),
            headers: {
                'Cookie': document.cookie,
                'Content-Type': 'application/json'
            },
            onload: function (response) {
                if (response.status === 200) {
                    const data = JSON.parse(response.responseText);
                    resolve(data['data']['dataList']['1']);
                } else {
                    reject(new Error('请求失败，状态码: ' + response.status));
                }
            },
            onerror: function (error) {
                reject(new Error('请求出错: ' + error));
            }
        });
    });
}

function sleep(ms: any) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
</script>

<style scoped></style> -->